/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.erp.ledger.account.controller;

import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.redragon.framework.springmvc.ControllerSupport;
import org.apache.commons.lang.StringUtils;
import org.hibernate.exception.ConstraintViolationException;
import org.redragon.framework.hibernate.data.RDDataBox;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.util.JsonDataUtil;
import org.redragon.framework.util.JsonUtil;

import com.erp.dataset.service.DatasetCommonService;
import com.erp.ledger.account.dao.data.DataBox;
import com.erp.ledger.account.dao.model.GLLedger;
import com.erp.ledger.account.dao.model.GLLedgerCO;
import com.erp.ledger.account.service.GLLedgerService;
import com.erp.masterdata.calendar.dao.model.MdFinanceCalendar;
import com.erp.masterdata.calendar.service.MdFinanceCalendarService;

@Controller
@RequestMapping("/web/gLLedger")
public class GLLedgerWebController extends ControllerSupport{
    
    //日志处理
    private Logger logger = LoggerFactory.getLogger(GLLedgerWebController.class);
    
    //服务层注入
    @Autowired
    private GLLedgerService gLLedgerService;
    @Autowired
    private DatasetCommonService datasetCommonService;
    @Autowired
    private MdFinanceCalendarService mdFinanceCalendarService;
    
    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getGLLedgerList");
    }
    
    
    
    /**
     * 
     * @description 查询数据列表
     * @date 2021-01-24 21:09:45
     * @author 
     * @param pages
     * @param gLLedgerCO
     * @param model
     * @return String
     *
     */
    @RequestMapping("getGLLedgerList")
    public String getGLLedgerList(Pages pages, GLLedgerCO gLLedgerCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        
        //分页查询数据
        List<GLLedger> gLLedgerList = this.gLLedgerService.getDataObjects(pages, gLLedgerCO);
        //循环设置会计日历
        for(GLLedger gLLedger: gLLedgerList) {
            MdFinanceCalendar mdFinanceCalendar = this.mdFinanceCalendarService.getDataObject(gLLedger.getCalendarCode());
            if(mdFinanceCalendar!=null) {
                gLLedger.setCalendarName(mdFinanceCalendar.getCalendarName());
            }
        }
        
        //审批状态
        Map approveStatusMap = RDDataBox.getApproveStatusMap();
        //币种
        Map currencyTypeMap = this.datasetCommonService.getCurrencyType();
        //会计方法
        Map accountingMethodMap = DataBox.getAccountingMethod();
        
        //页面属性设置
        model.addAttribute("gLLedgerList", gLLedgerList);
        model.addAttribute("pages", pages);
        model.addAttribute("approveStatusMap", approveStatusMap);
        model.addAttribute("currencyTypeMap", currencyTypeMap);
        model.addAttribute("accountingMethodMap", accountingMethodMap);
        
        return "basic.jsp?content=glLedger/ledgerList";
    }
    
    
    
    /**
     * 
     * @description 查询单条数据
     * @date 2021-01-24 21:09:45
     * @author 
     * @param gLLedger
     * @param model
     * @return String
     *
     */
    @RequestMapping("getGLLedger")
    public String getGLLedger(GLLedger gLLedger, Model model) {
        //查询要编辑的数据
        if(gLLedger!=null&&StringUtils.isNotBlank(gLLedger.getLedgerCode())) {
            GLLedger gLLedgerTemp = this.gLLedgerService.getDataObject(gLLedger.getLedgerCode());
            if(gLLedgerTemp!=null) {
                gLLedger = gLLedgerTemp;
            }
        }
        
        //审批状态
        Map approveStatusMap = RDDataBox.getApproveStatusMap();
        //币种
        Map currencyTypeMap = this.datasetCommonService.getCurrencyType();
        //会计方法
        Map accountingMethodMap = DataBox.getAccountingMethod();
        //会计日历
        List<MdFinanceCalendar> calendarList = this.mdFinanceCalendarService.getDataObjects();
        //会计科目结构
        Map accountingSubjectSegmentTypeMap = DataBox.getAccountingSubjectSegmentType();
        
        //页面属性设置
        model.addAttribute("gLLedger", gLLedger);
        model.addAttribute("approveStatusMap", approveStatusMap);
        model.addAttribute("currencyTypeMap", currencyTypeMap);
        model.addAttribute("accountingMethodMap", accountingMethodMap);
        model.addAttribute("calendarList", calendarList);
        model.addAttribute("accountingSubjectSegmentTypeMap", accountingSubjectSegmentTypeMap);
        
        return "basic.jsp?content=glLedger/ledgerEdit";
    }
    
    
    
    /**
     * 
     * @description 编辑数据
     * @date 2021-01-24 21:09:45
     * @author 
     * @param gLLedger
     * @param bindingResult
     * @param model
     * @return String
     *
     */
    @RequestMapping("editGLLedger")
    public String editGLLedger(@Valid GLLedger gLLedger, BindingResult bindingResult, Model model, RedirectAttributes attr) {
        //参数校验
        Map<String, String> errorMap = this.validateParameters(bindingResult, model);
        if(errorMap.size()>0) {
            return "forward:getGLLedger";
        }
        
        try {
            //对当前编辑的对象初始化默认的字段
            
            //保存编辑的数据
            this.gLLedgerService.insertOrUpdateDataObject(gLLedger);
            //提示信息
            attr.addFlashAttribute("hint", "success");
            attr.addAttribute("ledgerCode", gLLedger.getLedgerCode());
        }catch(Exception e){
            if(e.getCause().getClass()==ConstraintViolationException.class) {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                attr.addFlashAttribute("alertMessage", "分类账编码已存在，请重新输入");
                return "redirect:getGLLedgerList";
            }else {
                throw e;
            }
        }
        
        return "redirect:getGLLedger";
    }
    
    
    
    /**
     * 
     * @description 删除数据
     * @date 2021-01-24 21:09:45
     * @author 
     * @param gLLedger
     * @return String
     *
     */
    @RequestMapping("deleteGLLedger")
    public String deleteGLLedger(GLLedger gLLedger, RedirectAttributes attr) {
        //删除数据前验证数据
        if(gLLedger!=null&&gLLedger.getLedgerId()!=null&&StringUtils.isNotBlank(gLLedger.getLedgerCode())) {
            //TODO 根据日记账判定分类账簿是否使用
            boolean flag = true;
            
            if(flag) {
                //删除数据
                this.gLLedgerService.deleteDataObject(gLLedger);
                //提示信息
                attr.addFlashAttribute("hint", "success");
            }else {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                attr.addFlashAttribute("alertMessage", "分类账已使用，无法删除");
            }
        }
        
        return "redirect:getGLLedgerList";
    }
    
    
    
    /**
     * 
     * @description 更新审批状态
     * @date 2020年8月4日
     * @author dongbin
     * @param code
     * @param approveStatus
     * @param attr
     * @return
     * @return String
     *
     */
    @RequestMapping("updateApproveStatus")
    public String updateApproveStatus(String code, String approveStatus, RedirectAttributes attr) {
        
        if(StringUtils.isNotBlank(code)&&StringUtils.isNotBlank(approveStatus)) {
            //更新审核状态
            this.gLLedgerService.updateApproveStatus(code, approveStatus);
            //提示信息
            attr.addFlashAttribute("hint", "success");
            attr.addAttribute("ledgerCode", code);
        }else {
            //提示信息
            attr.addFlashAttribute("hint", "hint");
            attr.addFlashAttribute("alertMessage", "提交或审批数据错误");
            attr.addAttribute("ledgerCode", code);
        }
        
        return "redirect:getGLLedger";
    }
    
    
    
    /**
     * 
     * @description 获取分类账簿信息（异步）
     * @date 2021年2月9日
     * @author dongbin
     * @param ledgerCode
     * @return
     * @return String
     *
     */
    @RequestMapping("getGLLedgerInfoAjax")
    @ResponseBody
    public String getGLLedgerInfoAjax(String ledgerCode) {
        String json = "";
        
        //获取分类账信息
        GLLedger glLedger = this.gLLedgerService.getDataObject(ledgerCode);
        
        return JsonUtil.objectToJson(glLedger);
    }
}
